<template>
  <div class="app-container app-container-next app-container-detail">
    <el-card class="box-card site" shadow="false">
      <div slot="header" class="clearfix">
        <router-link :to="{name: 'tied-up-list'}">
          <el-button plain icon="el-icon-back" size="small" :round="true">
            返回
          </el-button>
        </router-link>
      </div>
      <el-row style="margin-top: 20px" v-loading="loading">
        <el-col :span="24">
          <el-form ref="tiedUpForm" :model="info" :rules="rules">
            <el-form-item label="捆绑内部名称：" prop="name">
              <el-input v-model="info.name" placeholder="请输入内部名称" style="width: 400px"/>
            </el-form-item>
            <el-form-item label="捆绑显示名称：" prop="displayName">
              <el-input v-model="info.displayName" placeholder="请输入显示名称" style="width: 400px"/>
            </el-form-item>
            <el-form-item prop="bundleSpuIdList" class="hasWidth inline-label">
              <template #label>
                <span @click="handleOpenDraw('bundleSpuIdList')">
                捆绑商品
                <el-button type="primary" size="mini"
                           style="margin-left: 12px">选择商品（{{ info.bundleSpuIdList.length }}）</el-button>
                  </span>
              </template>
              <pic-list :currentSpuList="info.bundleSpuIdList" @update="updateSupList($event, 'bundleSpuIdList')"></pic-list>
            </el-form-item>
            <el-form-item prop="applySpuIdList" class="hasWidth inline-label">
              <template #label>
                  <span>
                应用商品
                <el-button type="primary" size="mini" style="margin-left: 12px" @click="handleOpenDraw('applySpuIdList')">选择商品（{{ info.applySpuIdList.length }}）
                </el-button>
                    <el-button @click="handleCancelSelectAll" size="mini" style="margin-left: 12px" v-if="info.applySpuIdList.length">删除全部</el-button>
                  </span>
              </template>
              <pic-list :currentSpuList="info.applySpuIdList" @update="updateSupList($event, 'applySpuIdList')"></pic-list>
            </el-form-item>
            <el-form-item class="fixBottom">
              <el-button type="primary" @click="handleSubmit('tiedUpForm')" :loading="submitLoading">保存
              </el-button>
              <el-button @click="handleReset('tiedUpForm')">取消</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </el-card>
    <el-drawer
        size="1000px"
        title="商品选择"
        :wrapperClosable="false"
        :visible.sync="drawer1Visible"
        @close="handleClose"
        class="region-setting-panel series-drawer">
      <div style="padding-bottom: 20px;overflow: hidden" v-loading="loadingAllSpu">
        <el-form ref="form" label-width="80px" style="padding: 0">
          <el-form-item class="el-form--inline" style="margin-left: -70px;margin-bottom: 10px">
            <el-select v-model="pageSearch.spuSeries" placeholder="请选择" @change="searchSpuInfo(true)" style="width: 160px">
              <el-option
                  v-for="item in seriesOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
              </el-option>
            </el-select>
            <el-select v-model="pageSearch.spuType" placeholder="请选择" @change="searchSpuInfo(true)" style="width: 160px">
              <el-option value="" label="全部商品"></el-option>
              <el-option value="0" label="普通商品"></el-option>
              <el-option value="1" label="定制商品"></el-option>
            </el-select>
            <el-input v-model="pageSearch.spuName" placeholder="商品名称" style="width: 220px" @keyup.enter.native="searchSpuInfo(true)"></el-input>
<!--            <el-select v-model="pageSearch.published" placeholder="请选择" @change="searchSpuInfo(true)" style="width: 120px">
              <el-option
                  v-for="item in publishStatus"
                  :key="item.key"
                  :label="item.name"
                  :value="item.key">
              </el-option>
            </el-select>-->
            <el-input v-model="pageSearch.spuCode" placeholder="SPU编码,多个值以','分割"  @keyup.enter.native="searchSpuInfo(true)"  style="width: 220px"></el-input>
            <el-button type="primary" @click="searchSpuInfo(true)">搜索</el-button>
            <el-button @click="resetSearchInfo">重置</el-button>
          </el-form-item>
        </el-form>
        <el-table size="small" :data="productList" style="width: 100%;" height="height: 500px" v-if="productList.length"
                  v-el-height-adaptive-table="fixOption" @select="handleSelectionChange" @select-all="handleSelectionChangeAll"
                  v-loading="tableLoading" v-loadmore="loadMore"
                  ref="multipleTable">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column label="商品图片" slot="append" width="100px" fixed='left' align='left' >
            <template slot-scope="{row}">
              <el-button type="text" size="mini">
                <el-image
                    style="width: 60px; height: 40px;"
                    :src="row.spuImage"
                    :preview-src-list="[row.spuImage]"
                    fit="contain"></el-image>
              </el-button>
            </template>
          </el-table-column>
          <el-table-column prop="spuName" label="商品名称" :show-overflow-tooltip="true" width="380"></el-table-column>
          <el-table-column prop="sellPrice" label="售价">
            <template slot-scope="{row}">
              <p>{{ row.sellPrice|currency(currencySymbol) }}</p>
            </template>
          </el-table-column>
          <el-table-column prop="publishText" label="上架状态"></el-table-column>
        </el-table>
        <div class="footer" style="display: flex; justify-content: space-between;align-items: center;padding: 0 15px" v-if="productList.length">
          <span style="display: flex;align-items: center" v-if="typeName === 'applySpuIdList'"> <el-checkbox v-model="allSpuList" @change="handleCheckAllChange"  style="margin-right: 10px" />选择当前条件下所有商品</span>
          <div>
            <span style="font-weight: normal;margin-left: 12px;font-size: 14px">已选择{{ chooseProductList.length }}件商品</span>
            <el-button type="primary" @click="closeDrawerAndSaveData" :disabled="!this.chooseProductList.length">添加</el-button>
          </div>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import elHeightAdaptiveTable from '@/directives/el-table';
import picList from '../components/pic-list';
import {getSeriesPage} from '@/api/series';
import {addTiedUp} from '@/api/app-market';
import {getSpuAllPage, getSpuNewPage, getSpuPage} from '@/api/goods';
import {mapGetters} from 'vuex';

export default {
    name: 'tied-up-add',
    components: {picList},
    directives: {
        elHeightAdaptiveTable
    },
    data () {
        return {
            allSpuList: false,
            fixOption: {fixedHeader: true, bottomOffset: 80},
            drawer1Visible: false,
            loading: false,
            submitLoading: false,
            loadingAllSpu: false,
            typeName: 'bundleSpuIdList',
            info: {
                name: '',
                displayName: '',
                bundleSpuIdList: [],
                applySpuIdList: []
            },
            tableLoading: false,
            product: [],
            productList: [],
            chooseProductList: [],
            seriesOptions: [{id: '', name: '全部系列'}],
            publishStatus: [
                {key: '', name: '全部状态'},
                {key: 1, name: '上架'},
                {key: 0, name: '下架'},
                {key: -1, name: '未上架'}
            ],
            pageSearch: {
                page: 1,
                pageSize: 20,
                spuType: '',
                spuSeries: '',
                published: '',
                spuCode: '',
                spuName: '',
                notSpuIdList: '',
                bundleSale: true
            },
            rules: {
                name: [
                    {required: true, message: '请输入捆绑内部名称', trigger: 'blur'}
                ],
                displayName: [
                    {required: true, message: '请输入捆绑显示名称', trigger: 'blur'}
                ],
                bundleSpuIdList: [
                    {required: true, message: '请选择商品', trigger: 'blur'}
                ],
                applySpuIdList: [
                    {required: true, message: '请选择商品', trigger: 'blur'}
                ]
            }
        };
    },
    methods: {
        handleCheckAllChange (val) {
            if (val) {
                this.getAllSpuList();
            } else {
                this.chooseProductList = [];
                this.$nextTick(() => {
                    this.$refs.multipleTable.clearSelection();
                });
            }
        },
        loadMore () {
            console.log('el-table 已经滚到底部');
            this.pageSearch.page++;
            if (this.pageSearch.page > this.totalPage) {
                return;
            }
            this.searchSpuInfo();
        },
        getAllSeries () {
            let json = {
                page: 1,
                pageSize: 1000,
                siteId: this.siteId
            };
            getSeriesPage(json).then(res => {
                this.seriesOptions = [{id: '', name: '全部系列'}, ...res.records];
            });
        },
        handleOpenDraw (name) {
            this.pageSearch.bundleSale = name === 'applySpuIdList';
            this.drawer1Visible = true;
            this.typeName = name;
            this.product = this.info[name];
            this.searchSpuInfo(true);
            this.getAllSeries();
        },
        handleClose () {
            this.chooseProductList = [];
        },
        handleSelectionChange (rows, row) {
            let selected = rows.length && rows.indexOf(row) !== -1;
            let obj = {};
            let data = [...this.chooseProductList, ...rows].reduce((cur, next) => {
                // eslint-disable-next-line no-unused-expressions
                obj[next.id] ? '' : obj[next.id] = true && cur.push(next);
                return cur;
            }, []);
            const index = data.findIndex(s => s.id === row.id);
            if (!selected) {
                data.splice(index, 1);
            }
            this.chooseProductList = data;
            this.allSpuList = false;
        },
        handleSelectionChangeAll (rows) {
            this.allSpuList = false;
            this.chooseProductList = rows;
        },
        handleCancelSelectAll () {
            this.info.applySpuIdList = [];
        },
        async searchSpuInfo (flag = false) {
            if (flag) {
                this.pageSearch.page = 1;
            }
            this.tableLoading = true;
            this.pageSearch.siteId = this.siteId;
            this.pageSearch.notSpuIdList = this.typeName === 'bundleSpuIdList' ? this.info.bundleSpuIdList.map(res => res.spuId).join(',') : this.info.applySpuIdList.map(res => res.spuId).join(',');
            let data;
            if (this.typeName === 'bundleSpuIdList') {
                data = await getSpuPage(this.pageSearch);
            } else {
                data = await getSpuNewPage(this.pageSearch);
            }
            this.productList = flag ? data.records : this.productList.concat(data.records);
            this.totalPage = data.totalpage;
            this.tableLoading = false;
            this.$nextTick(() => {
                const list = this.productList.filter(s => this.chooseProductList.some(n => n.id === s.id));
                list.forEach(index => {
                    this.$refs.multipleTable.toggleRowSelection(index, true);
                });
            });
        },
        getAllSpuList () {
            this.loadingAllSpu = true;
            getSpuAllPage(this.pageSearch).then(res => {
                this.totalPage = res.totalpage;
                // this.productList = res.data;
                this.chooseProductList = res.data;
                this.loadingAllSpu = false;
                this.$nextTick(() => {
                    const list = this.productList.filter(s => this.chooseProductList.some(n => n.id === s.id));
                    list.forEach(index => {
                        this.$refs.multipleTable.toggleRowSelection(index, true);
                    });
                });
                console.log(res);
            }).catch(() => {
                this.loadingAllSpu = false;
            });
        },
        resetSearchInfo () {
            this.pageSearch = {
                page: 1,
                pageSize: 20,
                spuSeries: '',
                published: '',
                spuCode: '',
                spuType: '',
                spuName: '',
                notSpuIdList: '',
                bundleSale: this.typeName === 'applySpuIdList'
            };
            this.searchSpuInfo(true);
        },
        updateSupList (value, name) {
            this.info[name] = value;
        },
        // 保存
        handleSubmit (name) {
            this.$refs[name].validate(valid => {
                if (valid) {
                    const data = {
                        siteId: this.siteId,
                        name: this.info.name,
                        displayName: this.info.displayName,
                        applySpuIdList: this.info.applySpuIdList.map(res => res.spuId),
                        bundleSpuIdList: this.info.bundleSpuIdList.map(res => res.spuId)
                    };
                    this.submitLoading = true;
                    addTiedUp(data).then(res => {
                        this.$message.success('保存成功');
                        this.submitLoading = false;
                        this.$router.push({name: 'tied-up-list'});
                    }).catch(() => {
                        this.submitLoading = false;
                    });
                }
            });
        },
        closeDrawerAndSaveData () {
            if (this.typeName === 'bundleSpuIdList' && (this.info[this.typeName].length + this.chooseProductList.length) > 4) {
                this.$message.error('最多选择4个捆绑商品');
                return;
            }
            this.drawer1Visible = false;
            this.info[this.typeName] = this.info[this.typeName].concat(this.chooseProductList);
            this.productList = [];
            this.chooseProductList = [];
            this.allSpuList = false;
        },
        handleReset (name) {
            this.$refs[name].resetFields();
            this.$router.push({name: 'tied-up-list'});
        }
    },
    computed: {
        ...mapGetters(['siteList']),
        siteId () {
            return this.$store.state.user.siteId;
        },
        siteInfo () {
            let info = this.siteList.find(res => res.id === Number(this.siteId));
            return info;
        },
        currencySymbol () {
            return this.siteInfo.currencySymbol;
        }
    }
};
</script>

<style scoped>

</style>
